
import matplotlib
from scipy.io import wavfile
matplotlib.use('WXAgg')
from fractions import Fraction
import numpy

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure

import wx


class AudioSlicing(wx.Panel):
    
    def __init__(self, parent, model):
        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
        self.parent = parent
        self.model = model
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self, wx.ID_ANY, self.figure)
        self.option = wx.ComboBox(self, wx.ID_ANY, pos=(50, 170), size=(150, -1), choices=[], style=wx.CB_READONLY)
        self.option.Bind(wx.EVT_COMBOBOX, self.OnSelect)
        self.firstSlice = wx.Slider(self, wx.ID_ANY, 500, 0, 1000, wx.DefaultPosition, (250, -1),
                              wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
        self.firstSlice.Bind(wx.EVT_SLIDER, self.OnAdjustFirst)
        self.secondSlice = wx.Slider(self, wx.ID_ANY, 500, 0, 1000, wx.DefaultPosition, (250, -1),
                                     wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
        self.secondSlice.Bind(wx.EVT_SLIDER, self.OnAdjustSecond)
        save = wx.Button(self, 3, "Save")
        save.Bind(wx.EVT_BUTTON, self.OnSave)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.option, 0, wx.ALL, 5)
        sizer.Add(self.canvas, 0, wx.ALL, 5)
        sizer.Add(self.firstSlice, 0, wx.ALL, 5)
        sizer.Add(self.secondSlice, 0,wx.ALL, 5)
        sizer.Add(save, 0, wx.ALL, 5)

        self.SetSizer(sizer)
        self.value = 0

        self.secondValue = 500
        self.firstValue = 500
        self.firstLine = None
        self.secondLine = None
        self.span = None
        wx.EVT_COMBOBOX(self, 1, self.OnSelect)

    def OnSelect(self, event):
        self.axes.clear()
        filename = self.option.GetValue()
        location = self.model.getFile(filename)
        self.audio = self.model.getAudio(location)
        self.length = len(self.audio[1])
        x = numpy.array(range(0, len(self.audio[1])))
        self.plot = self.axes.plot(x, self.audio[1]/(2.0**15))
        self.figure.canvas.draw()
        self.length = len(self.audio[1])
        self.firstLine = None
        self.secondLine = None
        self.span = None
        self.firstSlice.SetValue(500)
        self.secondSlice.SetValue(500)
        self.firstValue = 500
        self.secondValue = 500

    def OnAdjustSecond(self, event):
        self.secondValue = self.secondSlice.GetValue()
        if self.secondLine != None:
            self.secondLine.remove()
        #print self.secondValue
        self.secondLine = self.axes.axvline(x=self.secondValue * self.length/1000)
        if self.span != None:
            self.span.remove()
        self.span = self.axes.axvspan(self.firstValue* self.length/1000, self.secondValue*self.length/1000, facecolor="g", alpha=0.5)
        self.figure.canvas.draw()

    def OnAdjustFirst(self, event):
        self.firstValue = self.firstSlice.GetValue()
        if self.firstLine != None:
            self.firstLine.remove()
        #print self.firstValue
        self.firstLine = self.axes.axvline(x=self.firstValue * self.length/1000)
        if self.span != None:
            self.span.remove()
        self.span = self.axes.axvspan(self.firstValue* self.length/1000, self.secondValue*self.length/1000, facecolor="g", alpha=0.5)
        self.figure.canvas.draw()

    def OnSave(self, event):
        dlg = wx.FileDialog(
            self, message="Choose a file",
            defaultFile="",
            style=wx.SAVE | wx.CHANGE_DIR
            )
        if dlg.ShowModal() == wx.ID_OK:
            #print self.audio[1][:self.value]
            path = dlg.GetPath()
            if self.firstValue > self.secondValue:
                audioSlice = self.audio[1][self.secondValue * self.length/1000: self.firstValue * self.length/1000]
            elif self.firstValue <= self.secondValue:
                audioSlice = self.audio[1][self.firstValue * self.length/1000: self.secondValue * self.length/1000]
            wavfile.write(path, self.audio[0], audioSlice.astype(self.audio[1].dtype))
        self.axes.clear()
        self.plot = self.axes.plot(self.audio[1])
        self.figure.canvas.draw()

    def update(self):
        self.option.Clear()
        filenames = self.model.getFilenames()
        for filename in filenames:
            self.option.Append(filename.keys()[0])
